package com.maben.udp.handler;

import com.maben.udp.service.UdpMessageService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * udp处理类
 */
@Component
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Resource
    private UdpMessageService messageService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        try {
            // 提取字节数组要放到主线程，放到异步就报错了!!!!
            final ByteBuf content = packet.content();
            int length = content.readableBytes();
            byte[] receivedBytes = new byte[length];
            content.readBytes(receivedBytes);
            final InetSocketAddress sender = packet.sender();

            // 异步处理消息，不阻塞接收线程
            messageService.processMessageAsync(receivedBytes, sender, ctx);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 全局异常处理
        cause.printStackTrace();
        ctx.close();
    }
}
    